package engine;

import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.LdapContext;

/**
 *
 * @author Pospishnyi Oleksandr
 */
public class LDAPManager {

	private String ldapServer;
	private String ldapServerPort;
	private DirContext ctx;

	public LDAPManager(String ldapServer, String ldapServerPort) {
		this.ldapServer = ldapServer;
		this.ldapServerPort = ldapServerPort;
		Hashtable env = new Hashtable();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, "ldap://" + ldapServer + ":" + ldapServerPort);
		env.put(Context.SECURITY_AUTHENTICATION, "none");
		env.put("com.sun.jndi.ldap.read.timeout", "5000");
		env.put("com.sun.jndi.ldap.connect.timeout", "5000");
		env.put(LdapContext.CONTROL_FACTORIES, "com.sun.jndi.ldap.ControlFactory");
		try {
			ctx = new InitialDirContext(env);
		} catch (NamingException ex) {
			Logger.getLogger(LDAPManager.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	public NamingEnumeration<SearchResult> retrive(String objectclass) {
		SearchControls ctls = new SearchControls();
		ctls.setReturningAttributes(null);
		ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
		try {
			return ctx.search("o=glue", "objectclass=" + objectclass, ctls);
		} catch (NamingException ex) {
			Logger.getLogger(LDAPManager.class.getName()).log(Level.SEVERE, null, ex);
			return null;
		}
	}

	public void close() {
		try {
			ctx.close();
		} catch (NamingException ex) {
			Logger.getLogger(LDAPManager.class.getName()).log(Level.SEVERE, null, ex);
		}
	}
}
